package com.itheima.reggie.web.controller;

import com.itheima.reggie.config.common.R;
import com.itheima.reggie.entity.User;
import com.itheima.reggie.service.UserService;
import com.itheima.reggie.utils.ValidateCodeUtils;
import com.itheima.reggie.web.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @Name UserController
 * @Author BaiXin
 * @Date 2022-11-03 18:18
 */
@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private HttpSession session;

    @Autowired
    RedisTemplate redisTemplate;

    /**
     * 短信发送验证码
     *
     * @param user
     * @return
     */
    @PostMapping("/sendMsg")
    public R sendValidateCode(@RequestBody User user) {

        //日志
        String phone = user.getPhone();
        log.debug("发送验证码，发送手机号为：[{}]", phone);

        //手机号校验
        if (phone.length() != 11) {
            throw new BusinessException("手机号格式有误，请重新输入");
        }
        String regPattern = "^((13[0-9])|(14[5,7,9])|(15([0-3]|[5-9]))|(166)|(17[0,1,3,5,6,7,8])|(18[0-9])|(19[8|9]))\\d{8}$";

        Pattern pattern = Pattern.compile(regPattern);

        Matcher matcher = pattern.matcher(phone);

        if (!matcher.matches()) {
            throw new BusinessException("手机号格式有误，请重新输入");
        }


        //随机验证码
        Integer code = ValidateCodeUtils.generateValidateCode(4);
        log.info("验证码：[{}]", code);

        //短信发送
        //SMSUtils.sendMessage(phone, code + "");

        //将验证码放入session
        session.setAttribute(phone, code);

        //将验证码保存到redis
        redisTemplate.opsForValue().set(phone,code.toString(),1, TimeUnit.MINUTES);

        //返回
        return R.success(code);
    }

    /**
     * 用户登录
     * @param map
     * @return
     */
    @PostMapping("/login")
    public R login(@RequestBody Map map) {

        //获取手机号
        String phone = map.get("phone").toString();

        //获取验证码
        String code = String.valueOf(map.get("code"));

        //从session中获取保存的验证码
//        String codeInSession = String.valueOf(session.getAttribute(phone));
        //从redis中获取验证码
        Object codeInSession = redisTemplate.opsForValue().get(phone);

        //比对验证码
        if (codeInSession == null || !codeInSession.equals(code)) {
            return R.error("验证码错误'");
        }
        //正确，根据手机号查询用户是否存在，不存在就添加
        User user = userService.checkAndRegisterUser(phone);

        session.setAttribute("userId", user.getId());

        //清除session中的验证码
        //session.removeAttribute(phone);

        //从redis中删除验证码
        redisTemplate.delete(phone);

        //返回数据
        return R.success("登录成功");
    }


}